'use client'

import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'react-hot-toast'
import api from '@/lib/api'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import Image from 'next/image'

interface SpotDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  spot?: {
    id: number
    name: string
    description: string
    location: string
    type: string
    open_time: string
    price: number
    images: string
    inventory: number
  } | null
  onSuccess: () => void
}

const SPOT_TYPES = [
  { value: '自然景观', label: '自然景观' },
  { value: '人文景观', label: '人文景观' },
]

export default function SpotDialog({
  open,
  onOpenChange,
  spot,
  onSuccess
}: SpotDialogProps) {
  const [imageFile, setImageFile] = useState<File | null>(null)
  const [previewUrl, setPreviewUrl] = useState<string>('')

  const form = useForm({
    defaultValues: {
      name: '',
      description: '',
      location: '',
      type: '自然景观',
      open_time: '',
      price: 0,
      inventory: 0
    }
  })

  useEffect(() => {
    if (spot) {
      form.reset({
        name: spot.name,
        description: spot.description,
        location: spot.location,
        type: spot.type,
        open_time: spot.open_time,
        price: spot.price,
        inventory: spot.inventory
      })
      setPreviewUrl(spot.images)
    } else {
      form.reset()
      setPreviewUrl('')
      setImageFile(null)
    }
  }, [spot, form])

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setImageFile(file)
      const url = URL.createObjectURL(file)
      setPreviewUrl(url)
    }
  }

  // 在组件卸载时清理预览URL
  useEffect(() => {
    return () => {
      if (previewUrl && previewUrl.startsWith('blob:')) {
        URL.revokeObjectURL(previewUrl)
      }
    }
  }, [previewUrl])

  const onSubmit = async (data: any) => {
    try {
      const formData = new FormData()
      // 添加所有表单字段
      formData.append('name', data.name)
      formData.append('description', data.description)
      formData.append('location', data.location)
      formData.append('type', data.type)
      formData.append('open_time', data.open_time)
      formData.append('price', data.price.toString())
      formData.append('inventory', data.inventory.toString())

      // 如果有新图片，添加到表单
      if (imageFile) {
        formData.append('image', imageFile)
      }

      if (spot) {
        await api.put(`/api/admin/spots/${spot.id}`, formData)
        toast.success('更新成功')
      } else {
        await api.post('/api/admin/spots', formData)
        toast.success('添加成功')
      }
      onSuccess()
    } catch (error) {
      toast.error(spot ? '更新失败' : '添加失败')
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{spot ? '编辑景点' : '添加景点'}</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="name"
                rules={{ required: '请输入景点名称' }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>名称</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="type"
                rules={{ required: '请选择景点类型' }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>类型</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="选择景点类型" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {SPOT_TYPES.map(type => (
                          <SelectItem key={type.value} value={type.value}>
                            {type.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="location"
                rules={{ required: '请输入景点地址' }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>地址</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="open_time"
                rules={{ required: '请输入开放时间' }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>开放时间</FormLabel>
                    <FormControl>
                      <Input {...field} placeholder="如：8:30-17:00" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="price"
                rules={{ 
                  required: '请输入门票价格',
                  min: { value: 0, message: '价格不能小于0' }
                }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>门票价格</FormLabel>
                    <FormControl>
                      <Input 
                        type="number" 
                        {...field}
                        onChange={e => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="inventory"
                rules={{ 
                  required: '请输入库存数量',
                  min: { value: 0, message: '库存不能小于0' }
                }}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>库存数量</FormLabel>
                    <FormControl>
                      <Input 
                        type="number" 
                        {...field}
                        onChange={e => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="description"
              rules={{ required: '请输入景点描述' }}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>描述</FormLabel>
                  <FormControl>
                    <Textarea {...field} rows={4} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div>
              <FormLabel>景点图片</FormLabel>
              <div className="mt-2 flex items-center gap-4">
                {previewUrl && (
                  <div className="relative h-40 w-60 border rounded-md overflow-hidden">
                    {previewUrl.startsWith('blob:') ? (
                      <img
                        src={previewUrl}
                        alt="Preview"
                        className="h-full w-full object-cover"
                      />
                    ) : (
                      <Image
                        src={previewUrl}
                        alt="Preview"
                        fill
                        className="object-cover"
                      />
                    )}
                  </div>
                )}
                <Input
                  type="file"
                  accept="image/*"
                  onChange={handleImageChange}
                  className="max-w-xs"
                />
              </div>
            </div>

            <div className="flex justify-end space-x-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
              >
                取消
              </Button>
              <Button type="submit">
                {spot ? '保存' : '添加'}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 